using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class JoystickScript : MonoBehaviour
{
    //摇杆圆点
    public GameObject joystickDot;
    // Start is called before the first frame update
    void Start()
    {
        GetComponent<SpriteRenderer>().enabled = false;
        //设置摇杆圆点不可见
        joystickDot.GetComponent<SpriteRenderer>().enabled = false;
    }

    // Update is called once per frame
    void Update()
    {
        //如果触摸屏幕
        // Debug.Log("Input.touchCount:" + Input.touchCount);
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            //获取按下的屏幕的坐标
            Vector3 touchPos = touch.position;
            touchPos = Camera.main.ScreenToWorldPoint(touchPos);
            touchPos.z = 0;
            //状态
            // Debug.Log("touch.phase:" + touch.phase);
            switch (touch.phase)
            {
                case TouchPhase.Began:
                    //设置为可见
                    GetComponent<SpriteRenderer>().enabled = true;
                    //设置摇杆圆点可见
                    joystickDot.GetComponent<SpriteRenderer>().enabled = true;
                    MoveToTouchPos(touchPos);
                    MoveJoystickDot(touchPos);
                    break;
                case TouchPhase.Ended:
                    //设置为不可见
                    GetComponent<SpriteRenderer>().enabled = false;
                    //设置摇杆圆点不可见
                    joystickDot.GetComponent<SpriteRenderer>().enabled = false;
                    //摇杆圆点回到中心
                    joystickDot.transform.position = transform.position;
                    break;
                case TouchPhase.Moved:
                    MoveJoystickDot(touchPos);
                    break;
                case TouchPhase.Stationary:
                    break;
            }
        }
    }

    private void MoveToTouchPos(Vector3 touchPos)
    {
        // Debug.Log("touchPos:" + touchPos);
        //移动当前节点到指定位置
        transform.position = touchPos;
    }

    private void MoveJoystickDot(Vector3 touchPos)
    {
        //中心点
        Vector3 centerPos = transform.position;
        //计算摇杆圆点的位置
        Vector3 dir = touchPos - centerPos;
        //获取节点的宽度
        float width = GetComponent<SpriteRenderer>().bounds.size.x;
        //设置摇杆圆点的宽度
        float dotWidth = joystickDot.GetComponent<SpriteRenderer>().bounds.size.x;
        //摇杆圆点的位置不能超出摇杆的范围
        float maxDistance = width / 2 - dotWidth / 2;
        //计算摇杆圆点的位置
        if (dir.magnitude > maxDistance)
        {
            dir = dir.normalized * maxDistance;
        }
        joystickDot.transform.position = centerPos + dir;
    }

    public Vector3 GetMoveDirection()
    {
        //中心点
        Vector3 centerPos = transform.position;
        //摇杆圆点的位置
        Vector3 dotPos = joystickDot.transform.position;
        //计算摇杆圆点的位置
        Vector3 dir = dotPos - centerPos;
        return dir;
    }

}
